/*Author: Seungbeom Ma
 *SJSU 
 * DATE: NOV 16
 * */
package com.example.projectmobilecloud;

import java.text.DecimalFormat;
import java.util.ArrayList;

import tool.http.networks.DataCommunication;
import tool.threads.HttpThread;
import tool.threads.LocalPerformThread;
import tool.threads.LocalThread;
import tool.workflow.Graph;
import tool.workflow.WorkFlowBuilder;
import tool.writefile.ReportBuilder;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
		

public class ControlActivity extends Activity {
    	private WorkFlowBuilder  wfb = new WorkFlowBuilder();
    	private DataCommunication dc = new DataCommunication();
    	private ReportBuilder rb;
    	private MainActivity ma = new MainActivity();
    	private TextView tv1 = null;
    	
    	// for testing performance
    	private boolean Is_Local = true;
    	//
    	
		public void onCreate(Bundle si){
			
			super.onCreate(si);		
			setContentView(R.layout.control_main);
	        Bundle bundle = getIntent().getExtras();
			int WORK_FLOWS = bundle.getInt("WORKFLOW_NUMBERS");
			int SERVICE_OPTION = bundle.getInt("RUNNING_MODE");
			int Energy_Test_OPTION = bundle.getInt("Energy_id");
			boolean Is_Energy_Check = bundle.getBoolean("Is_Energy_checked");
			boolean Is_CM_Check = bundle.getBoolean("Is_Energy_custom");
			boolean Is_CM_MB_Check = bundle.getBoolean("is_CM_MB_Checked");
			int CM_PRO_Amount = bundle.getInt("CM_VALUE");
			System.out.println("WORK_FLOWS " + WORK_FLOWS);
			System.out.println("SERVICE_OPTION " + SERVICE_OPTION);
			System.out.println("Energy_id " + Energy_Test_OPTION);
			System.out.println("CM_PRO_Amount " + CM_PRO_Amount);
			System.out.println("Is_Energy_checked " + Is_Energy_Check);
			System.out.println("Is_CM_Check " + Is_CM_Check);
			System.out.println("Is_CM_MB_Check " + Is_CM_MB_Check);
			
			Run_Service(SERVICE_OPTION,WORK_FLOWS ,Energy_Test_OPTION,CM_PRO_Amount,Is_CM_Check ,Is_Energy_Check, Is_CM_MB_Check);

		}
		
		
		public void Run_Service(int SERVICE_OPTION , int WORK_FLOWS , int Eenegy_Option , int CM_Value , boolean Is_CM_CK ,
				boolean Is_Eenegy_Checked , boolean Is_CM_MB_Check){
			   
		
			// if case is only local or cloud 
			
			long tStart = System.currentTimeMillis();
			//Energy Test
			if(Is_Eenegy_Checked)
			{
				Log.d("Local Energy Thread" ,"Start");
				Graph g = wfb.Energy_Test_Graph_Builder(Eenegy_Option);
				
				
					Log.d("Local Energy Thread" ,"DONE");	
					LocalPerformThread lpt = new LocalPerformThread(dc.PacketBuilder(g));
					lpt.start();
					try {
						lpt.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Log.d("Local Energy Thread" ,"DONE");	
				
			
			     Display_Energy_Result(Eenegy_Option, get_End_Time(tStart) , "Local");
			}
			else if(Is_CM_CK){
				// Running Node by User Options
				Log.d("CM Thread" ,"Start");
				 ArrayList<Thread> threads = new ArrayList<Thread>();
				Graph g = wfb.Build_Custom_Single_Node(CM_Value);
				if(Is_CM_MB_Check == false){
				Log.d("Local Mode", "Start");	
				LocalPerformThread lpt = new LocalPerformThread(dc.PacketBuilder(g));
				lpt.start();
			
				 threads.add(lpt);
				
				 for(int i = 0 ; i < threads.size(); i++){
					 Thread t = threads.get(i);		 
					 try {
						t.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				 }
				 Display_Energy_Result(CM_Value,get_End_Time(tStart) ,"Local Mode");
				}
				else{
					Log.d("Cloud Mode", "Start");	
					HttpThread ht = new HttpThread(1,dc.PacketBuilder(g));
					ht.start();
					
					try {
						ht.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Log.d("Cloud Energy Thread" ,"DONE");
					 Display_Energy_Result(CM_Value,get_End_Time(tStart) ,"Cloud");
				}
			}
			else{
				// Local Time consume test
				if(WORK_FLOWS == 3){
					if(Is_Local == true)
					{
						ArrayList<String> display_list = new ArrayList<String>();
						Log.d("Performance Test" , "Local Mode with Const Value");
						ArrayList<Graph> graph_al = wfb.Time_Test_Graph_Builder();
						ArrayList<String> str_al = new ArrayList<String>();
						String Task_Size = "";
						for(int i = 0 ; i < graph_al.size() ; i++ ){
							long local_tStart = System.currentTimeMillis();
							LocalPerformThread lpt = new LocalPerformThread(dc.PacketBuilder(graph_al.get(i)));
							lpt.start();
							try {
								lpt.join();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						    long local_tEnd = System.currentTimeMillis();
					    	long local_tDelta = local_tEnd - local_tStart;
					      	double local_elapsedSeconds = local_tDelta / 1000.0;
							str_al.add(String.valueOf(local_elapsedSeconds));
						}
						DecimalFormat df = new DecimalFormat("#.#####");
//						ArrayList<String> Task_Sizes = new ArrayList<String>();
//						ArrayList<String> Ex_Times = new ArrayList<String>();
//						ArrayList<String> Del_Times = new ArrayList<String>();
						for(int ii = 0 ; ii < str_al.size() ; ii++){
							Task_Size = "S-"+  ((ii +1)*3000)+ "-T-" + str_al.get(ii);
							System.out.print("S-"+  ((ii +1)*3000)+ "-T-" + str_al.get(ii));
							if( ii >= 1){
								display_list.add(Task_Size + "-D-"  + df.format((Double.parseDouble(str_al.get(ii)) - Double.parseDouble(str_al.get(ii-1))))+"\n");
								System.out.println("-D-"  + df.format((Double.parseDouble(str_al.get(ii)) - Double.parseDouble(str_al.get(ii-1)))));
							}
							else{
								display_list.add(Task_Size + "-D-0 \n");
								System.out.println("-D-0");
							}
						}
						Display_Preform_Result(display_list);
					}
					else{
					
					}
					
						
				}
				else if(SERVICE_OPTION == 2){
					// cloud test
					Log.d("Cloud Service" , "HT starts to run");
					 final Graph workflow = wfb.SetWorkFlow(WORK_FLOWS);
					HttpThread ht = new HttpThread(1,dc.PacketBuilder(workflow));
					ht.start();
					try {
						ht.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("Done with Thread");
					String result = ht.getValue();	
					Log.d("HT Thead Result", result);	
				}
				else if(SERVICE_OPTION== 1){
					// local test
					Log.d("Local Service" , "HT starts to run");
					 final Graph workflow = wfb.SetWorkFlow(WORK_FLOWS);
					LocalThread lt = new LocalThread(dc.PacketBuilder(workflow));
					lt.start();
					try {
						lt.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String result = lt.getValue();
					Log.d("LT Thead Result", result);
				}
				else{
					// Hell
					Log.d("Extra", "Local & Cloud Operation");
					final Graph gs =  wfb.SetWorkFlow(WORK_FLOWS);
					
					LocalThread lta = new LocalThread(dc.Double_Pucket_Builder(gs).get(0));
					HttpThread hta = new HttpThread(1,dc.Double_Pucket_Builder(gs).get(1));
					HttpThread htaa = new HttpThread(2,dc.Double_Pucket_Builder(gs).get(2));
					hta.start();
					htaa.start();
					lta.start();
					try {
	
						hta.join();
						htaa.join();
						lta.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
				}
				// display result
				if (WORK_FLOWS != 3){
					    long tEnd = System.currentTimeMillis();
				    	long tDelta = tEnd - tStart;
				      	double elapsedSeconds = tDelta / 1000.0;
				        System.out.println("Time Cost: " +  elapsedSeconds);
				        tv1 = (TextView)findViewById(R.id.tv);
				        tv1.setText("elapsedSeconds " + elapsedSeconds);
				}
			}

		        Log.d("Building Report", "Processing");     
		}
		
		public String Run_Performance_Test(boolean is_costant){
			final Graph workflow = wfb.Set_Perfomance_Test_Node();
			String result="";
			Log.d("Run_Performance_Test", "Running only one task");
			if(is_costant == true){
				Log.d("Run_Performance_Test", "Setting Constant Numbers");
			}
			else{
				
				Log.d("Run_Performance_Test", "Setting Random Numbers");
				LocalThread lt = new LocalThread(dc.PacketBuilder(workflow));
				lt.start();
				try {
					lt.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 result = lt.getValue();
			}
			return result;
		}
		
		
		// Helper function to make display message
		
		public String Text_View_Builder(double run_time , double e_consume ,int Run_Mode, int Run_Nodes ){
			String re_str = "";
			re_str =  Run_time_Selection(Run_Mode) + "\n" + NODE_Selection(Run_Nodes) + "\n" + "Run Time: "
					+ String.valueOf(run_time) + "\n" + "Energy Consume: " + e_consume;
		
			return re_str;
		}
		
		
		public String Run_time_Selection(int Run_Mode){
			String re_str = "";
			if(Run_Mode == 1){
				re_str = "LOCAL MODE";
			}
			else if(Run_Mode== 2){
				re_str = "CLOUD MODE";
			}
			else if(Run_Mode == 3){
				re_str = "COMBI MODE";
			}
			else{
				re_str = "WTF MODE";
			}
			
			return re_str;
		}
		
		
		public String NODE_Selection(int Run_Mode){
			String re_str = "";
			if(Run_Mode == 1){
				re_str = "NODE: 30";
			}
			else if(Run_Mode== 2){
				re_str = "NODE: 60";
			}
			else if(Run_Mode == 3){
				re_str = "NODE: 100";
			}
			else{
				re_str = "NODE: WTF";
			}
			
			return re_str;
		}
		
		public double get_End_Time(long st){
			 long tEnd = System.currentTimeMillis();
		     long tDelta = tEnd - st;
		     return tDelta / 1000.0;
		}
		
		public void Display_Energy_Result(int test_option , double time , String TEST_MODE){
			int result = 0;
			result = (test_option >200000000) ? (test_option-2131165194): test_option;
				
			String display ="Test Mode " + TEST_MODE+ "\n"+  "Energy Test option: "+ result+"\n" +" it was running for " + time;
			tv1 = (TextView)findViewById(R.id.tv);
	        tv1.setText(display);
		}
		public void Display_Preform_Result(ArrayList<String> dis_list){
			String display = "Preform test reuslts \nTask Size-Time Consumption-Delta \n \n";
			for(int i = 0 ; i < dis_list.size(); i++){
				display += dis_list.get(i);
			}
			tv1 = (TextView)findViewById(R.id.tv);
	        tv1.setText(display);
		}
}
